package model

import (
	"database/sql"

	"alolang.org.cn/api/server/config"
	"alolang.org.cn/api/server/log"
	_ "github.com/go-sql-driver/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	sqlDB  *sql.DB
	gormDB *gorm.DB
)

func DBInit() {
	sqlDBInit("mysql", config.Server.MySQL.DSN)
	gormDBInit()
}

func sqlDBInit(driverName, dataSourceName string) {
	if sqlDB != nil {
		log.Logger.Panic("sqlDB is already initialized")
	}
	var db *sql.DB
	var err error
	db, err = sql.Open(driverName, dataSourceName)
	if err != nil {
		log.Logger.Panicf("Invalid DSN passing to sql driver: %s", err.Error())
	}
	sqlDB = db
}

func DBClose() {
	if sqlDB == nil {
		return
	}
	if err := sqlDB.Close(); err != nil {
		log.Logger.Errorf("Close sqlDB error: %s", err.Error())
	}
	sqlDB = nil
}

func gormDBInit() {
	if sqlDB == nil {
		log.Logger.Panic("sqlDB is not initialized")
	}
	gormdb, err := gorm.Open(mysql.New(mysql.Config{
		Conn: sqlDB,
	}), &gorm.Config{})
	if err != nil {
		log.Logger.Panicf("Initialize gormDB error: %s", err.Error())
	}
	gormDB = gormdb.Debug()
	gormDB.AutoMigrate(User{})
	gormDB.AutoMigrate(PackageInfo{})
}
